<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>国际化语言插件</title>
</head>

<body>
    <div id="app">
        <h2>
            实现一个国际化语言转换插件，实现的效果为：向插件传入一个短语，插件会自动根据当前设置的语言环境
            来显示出正确的翻译结果。
            <h2>使用实例挂载函数：</h2>
            <h3>{{$translateLang('greeting')}}</h3>
            <h2>使用指令：</h2>
            <h3 v-tranlang:[lang]="'goodbye'"></h3>
            <button @click="changeLang('english')">英文环境</button>
            <button @click="changeLang('simpleCh')">简体中文环境</button>
            <button @click="changeLang('duplicateCh')">繁体中文环境</button>
        </h2>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script>
        const langGreetingMap = {
            english: {
                greeting: "hello！",
                goodbye: "See you！"
            },
            simpleCh: {
                greeting: "您好",
                goodbye: "再见！"
            },
            duplicateCh: {
                greeting: "妳好",
                goodbye: "再見!"
            }
        };
        const interLangPlugin = {
            install(Vue, langMap) {
                // 插件在全局初始化时在原型链上挂载方法
                Vue.prototype.$translateLang = function (msg) {
                    console.log(langMap);// 拿到相应的option参数
                    return langMap[this.lang][msg]
                };
                // 插件在全局初始化时注册自定义指令
                Vue.directive("tranlang", (el, binding) => {
                    el.textContent = langMap[binding.arg][binding.value];
                });
            }
        };

        Vue.use(interLangPlugin,langGreetingMap);// 将语言map数据作为插件options传入

        new Vue({
            el: '#app',
            data() {
                return {
                    lang: "english"
                }
            },
            methods: {
                changeLang(lang) {
                    this.lang = lang;
                }
            }
        });

    </script>
</body>

</html>